module WWW
  class Tkd
    class TbSellerOrder < ActiveRecord::Base
      #判断订单是否存在
      def self.find_from_order_id_and_user_id(order_id,user_id)
        return self.find_by_order_id_and_user_id(order_id,user_id)
      end
      #根据tid与user_id获得订单信息
      def self.find_from_tid_and_user_id(tid,user_id)
        order = WWW::Tkd::TbOrder.find_by_tid tid#这里可能遇到t_order没有的记录哦
        if order!=nil
          seller_order  = self.find_from_order_id_and_user_id(order.id,user_id)
          if seller_order==nil
            seller_order = self.new
            seller_order.user_id=user_id
            seller_order.order_id=order.id
            seller_order.is_newer=0
            seller_order.save
          end
          return seller_order
        end
        return nil
      end
      #订单与卖家进行关联
      def self.relate_order_to_seller order,session
        #将order与user关联到seller_order表中
        seller_order = self.find_by_user_id_and_order_id(session[:id],order.id)
        if seller_order==nil
          seller_order=self.new
          seller_order.user_id=session[:id]
          seller_order.order_id=order.id
          seller_order.save
        end
      end
      #将Taobao的数据导入到tb_order表中，并与tb_seller_order进行关联
      def self.save_from_tabao items,session
        if items['trade']!=nil
          items['trade'].each do|item|
            order = WWW::Tkd::TbOrder.find_by_tid item['tid'][0].strip().to_s
            if order==nil#新订单
              orders = WWW::Tkd::Gold::Utils::Misc.parse_trade item
              orders.each do|item|
                item.save
                relate_order_to_seller item,session
              end
            else
              relate_order_to_seller order,session
            end
          end
        end
      end
    end
  end
end
